import * as c from '@/services/consts';
import * as api from '@/services/report';
import * as utils from '@/utils/utils';
import { PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Space, Tag } from 'antd';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef } from 'react';
dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';

const VpnGroupTreeList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  let regEnd = dayjs().format(dateFormat); //Date.now();
  let regBegin = dayjs().add(-7, 'day').format(dateFormat); //Date.now() - 1000 * 60 * 60 * 24 * 7
  console.log(regBegin, regEnd);

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.retainStat(params, undefined, filter);
    if (result.success) {
    }

    return Promise.resolve(result);
  };

  const displayCount = (
    list: number[] | undefined,
    pos: number,
    total: number,
  ) => {
    let defVal = '-';
    if(total < 1) return defVal;
    if (!list) return defVal;
    if (list.length < pos) return defVal;
    if (list[pos] == -1) return defVal;
    return (
      <>
        {utils.formatNumber(list[pos])}{' '}
        <Tag>
          {list[pos] == 0 ? '0%' : `${((list[pos] * 100) / total).toFixed(2)}%`}
        </Tag>
      </>
    );
  };

  let columns: ProColumns<API.RetainStat>[] = [
    {
      title: '日期',
      align: 'center',
      dataIndex: 'title',
      width: 200,
      hideInSearch: true,
    },
    {
      title: '新增',
      align: 'center',
      dataIndex: 'count',
      hideInSearch: true,
      renderText: (val) => {
        return utils.formatNumber(val);
      },
    },
    {
      title: '1日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 0, record.count ?? 1);
      },
    },
    {
      title: '2日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 1, record.count ?? 1);
      },
    },
    {
      title: '3日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 2, record.count ?? 1);
      },
    },
    {
      title: '4日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 3, record.count ?? 1);
      },
    },
    {
      title: '5日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 4, record.count ?? 1);
      },
    },
    {
      title: '6日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 5, record.count ?? 1);
      },
    },
    {
      title: '7日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 6, record.count ?? 1);
      },
    },
    {
      title: '统计时间',
      dataIndex: 'eventStartTime_at',
      valueType: 'dateRange',
      fieldProps: {
        format: dateFormat,
        allowEmpty: false,
        allowClear: false,
        // defaultValue:{[dayjs('2015/01/01'), dayjs('2015/01/01')]}
      },
      initialValue: [regBegin, regEnd],
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            registBegin: value[0],
            registEnd: value[1],
          };
        },
      },
    },
    {
      title: '分组',
      dataIndex: 'group',
      hideInTable: true,
      valueType: 'select',
      initialValue: 'country',
      fieldProps: {
        allowClear: false,
        options: [
          { label: '按国家分组', value: 'country' },
          { label: '按渠道分组', value: 'channel' },
        ],
      },
    },
    {
      title: '渠道',
      dataIndex: 'channels',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        allowClear: true,
        options: [
          { label: 'google', value: 'google' },
          { label: 'apple', value: 'apple' },
          { label: 'universal', value: 'universal' },
        ],
      },
    },
    {
      title: '国家',
      dataIndex: 'countrys',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        allowClear: true,
        options: c.Countrys.map((val) => {
          return { label: val, value: val };
        }),
      },
    },
  ];

  let childrenColumns: ProColumns<API.RetainStat>[] = [
    {
      title: '名称',
      dataIndex: 'title',
      width: 210,
    },
    {
      title: '新增',
      align: 'center',
      dataIndex: 'count',
      renderText: (val) => {
        return utils.formatNumber(val);
      },
    },
    {
      title: '1日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 0, record.count ?? 1);
      },
    },
    {
      title: '2日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 1, record.count ?? 1);
      },
    },
    {
      title: '3日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 2, record.count ?? 1);
      },
    },
    {
      title: '4日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 3, record.count ?? 1);
      },
    },
    {
      title: '5日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 4, record.count ?? 1);
      },
    },
    {
      title: '6日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 5, record.count ?? 1);
      },
    },
    {
      title: '7日留存',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return displayCount(record?.days, 6, record.count ?? 1);
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RetainStat>
        rowKey="title"
        actionRef={actionRef}
        formRef={formRef}
        options={{
          fullScreen: false,
          reload: false,
          // setting: false,
          density: false,
          // search:true,
          // setting: {
          //   listsHeight: 500,
          // },
        }}
        // loading={dataLoading}
        search={{
          // labelWidth: 80,
          defaultCollapsed: false,
          span: 4,
        }}
        pagination={false}
        columns={columns}
        columnsState={undefined}
        // columnsState={{
        //   value: columnsStateMap,
        //   onChange: setColumnsStateMap,
        // }}
        expandable={{
          expandedRowRender: (record) => (
            <ProTable
              columns={childrenColumns}
              headerTitle={false}
              search={false}
              options={false}
              dataSource={record.countrys}
              tableStyle={{ marginLeft: 10 }}
              pagination={false}
            />
          ),
          defaultExpandedRowKeys: ['0'],
        }}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              ></Space>
            </>
          ),
          // menu: {
          //   type: 'tab',
          //   activeKey: productId,
          //   items: productMenuItems,
          //   onChange: (tabKey) => {
          //     setProductId(tabKey as string);
          //   },
          // },
        }}
        // dataSource={monitorData?.data}
        // params={{
        //   // registBegin:'2023-4-20',
        //   // registEnd:'2023-4-25'api.retainStat
        // }}
        request={loadData}
      />
    </PageContainer>
  );
};

export default VpnGroupTreeList;
